package com.mocai.merchant.spring.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 日志记录切面
 */
public class LogAspect extends AspectTemplate {
    final Logger logger = LoggerFactory.getLogger(LogAspect.class);
    StringBuffer logContent = new StringBuffer();

    @Override
    protected Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        String typeName = signature.getDeclaringTypeName();
        String name = signature.getName();
        Object[] args = pjp.getArgs();
        logContent.append(System.lineSeparator()).append("======> 调用接口名：");
        logContent.append(typeName + "." + name + "(");
        if (null != args && args.length > 0) {
            logContent.append(args[0].getClass().getSimpleName());
            for (int i = 1; i < args.length; i++) {
                logContent.append(", ").append(args[i].getClass().getSimpleName());
            }
        }
        logContent.append(")");
        // 打印请求接口
        String methodString = logContent.toString();
        logContent.setLength(0);
        logContent.append(methodString).append(System.lineSeparator()).append("======> 请求参数：").append(JSON.toJSONString(args));
        logger.debug(logContent.toString());
        logContent.setLength(0);
        // 发送请求
        Object returnValue = pjp.proceed();
        // 打印返回值
        logContent.append(System.lineSeparator()).append("<====== 返回值：").append(JSON.toJSONString(returnValue));
        logger.debug(logContent.toString());
        logContent.setLength(0);
        return returnValue;
    }
}
